import { Region } from '~/server/models/region'

export default defineEventHandler(async (event: any) => {
  try {
    const id = event.context.params?.id
    
    // 获取要删除的地区信息
    const region = await Region.findOne({
      where: { id: Number(id) }
    })
    
    if (!region) {
      throw createError({
        statusCode: 404,
        message: '地区不存在'
      })
    }

    // 递归删除所有子地区
    await deleteRegionAndChildren(region.code)
    
    return {
      success: true
    }
  } catch (error) {
    throw error
  }
})

// 递归删除地区及其子地区
async function deleteRegionAndChildren(parentCode: string) {
  // 获取所有子地区
  const children = await Region.findAll({
    where: {
      parentCode
    }
  })

  // 递归删除子地区
  for (const child of children) {
    await deleteRegionAndChildren(child.code)
  }

  // 删除当前地区
  await Region.destroy({
    where: {
      code: parentCode
    }
  })
} 